package com.example.dragandview;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class MainRecyclerViewAdapter extends RecyclerView.Adapter<MainRecyclerViewAdapter.MyViewHodler> {
    private final Context context;
    private ArrayList<String> datas;

    public MainRecyclerViewAdapter(Context context,ArrayList<String> data) {
        this.context = context;
        this.datas = data;
    }

    @NonNull
    @Override
    public MyViewHodler onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = View.inflate(context,R.layout.layout_mainpage_content,null);
        return new MyViewHodler(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHodler holder, int position) {
        String data = datas.get(position);
        holder.textView.setText(data);
    }

    @Override
    public int getItemCount() {
        return datas.size();
    }

    class MyViewHodler extends RecyclerView.ViewHolder{
        private TextView textView;
        public MyViewHodler(View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.textview_mainpage_content);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(onItemClickListener != null){
                        onItemClickListener.onItemClick(v,datas.get(getLayoutPosition()));
                    }
                    System.out.println("我点击了"+datas.get(getLayoutPosition()));
                }
            });
        }
    }
    /**
     * 点击recyclerView来监听
     */
    public interface OnItemClickListener{
        public void onItemClick(View view,String data);
    }
    private OnItemClickListener onItemClickListener;
    public void setOnItemClickListener(OnItemClickListener onItemClickListener){
        this.onItemClickListener = onItemClickListener;
    }
}
